//Memory.scala
package test

import chisel3._
import chisel3.util._

class DataMemory{
  val dmem = Mem(256, UInt(32.W))
  def read(addr: UInt): UInt = { Mux(addr === 0.U, 0.U, dmem(addr)) }
  def write(wen: Bool, addr: UInt, data: UInt): Unit = { dmem(Mux(wen, addr, 0.U)) := data }
}

class Memory extends Module{
  val io = IO(new Bundle{
    val exmem = Input(new EXMEM)
    val memwb = Output(new MEMWB)

    val RD_mem = Output(new ReDirection)
  })

  val mems = RegNext(io.exmem)

  val datamemory = new DataMemory
  datamemory.write(mems.store, mems.aluresult(10,2), mems.storeData)
  val loadData = datamemory.read(mems.aluresult(10,2))

  io.memwb.Valid := mems.Valid
  io.memwb.Inst := mems.Inst
  io.memwb.PC := mems.PC
  io.memwb.wbdata := Mux(mems.load, loadData, mems.aluresult)
  io.memwb.wen := mems.wen
  io.memwb.regdes := mems.regdes

  io.RD_mem.wen := mems.wen
  io.RD_mem.regdes := mems.regdes
  io.RD_mem.wbdata := io.memwb.wbdata
}

